package com.project.auth.service.impl;

import com.project.auth.model.system.SysUser;
import com.project.auth.service.SysUserService;
import com.project.security.custom.CustomUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * @Description
 * @Author : XIAOMING
 * @create 2023/4/24 17:32
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 根据用户名获取用户对象（获取不到直接抛异常）
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询
        SysUser sysUser = sysUserService.getByUsername(username);
        //如果查询不到数据就通过抛出异常来给出提示
        if (null == sysUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        if (sysUser.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }
        //封装成UserDetails对象返回
        return new CustomUser(sysUser, Collections.emptyList());
    }

}
